//
//  ViewController.swift
//  UIImagePickerController
//
//  Created by 晨风 on 2019/7/2.
//  Copyright © 2019 levy. All rights reserved.
//

import UIKit
import MobileCoreServices

class ViewController: UIViewController {
    
    @IBOutlet weak var TakePhoto: UIButton!
    @IBOutlet weak var TakeVideoBtn: UIButton!
    @IBOutlet weak var TakeVideoBtn2: UIButton!
    @IBOutlet weak var ViewLibraryBtn: UIButton!
    @IBOutlet weak var IMGPreview: UIImageView!
    
    
    let videoFileName = "/video.mp4"
    override func viewDidLoad() {
        super.viewDidLoad()
        self.TakePhoto.layer.cornerRadius = 5.0
        self.TakePhoto.clipsToBounds = true
        self.TakeVideoBtn.layer.cornerRadius = 5.0
        self.TakeVideoBtn.clipsToBounds = true
        self.TakeVideoBtn2.layer.cornerRadius = 5.0
        self.TakeVideoBtn2.clipsToBounds = true
        self.ViewLibraryBtn.layer.cornerRadius = 5.0
        self.ViewLibraryBtn.clipsToBounds = true
        self.title = "系统相册、拍照拍视频"
    }

    /// 拍照片
    @IBAction func TakePhoto(_ sender: Any) {
        // 1 检查相机权限
        if UIImagePickerController.isSourceTypeAvailable(.camera) {
            let vc = UIImagePickerController.init()
            vc.sourceType = .camera
            self.navigationController?.present(vc, animated: true, completion: {
            })
            vc.delegate = self as UIImagePickerControllerDelegate & UINavigationControllerDelegate
        }
        else {
            print("Camera is not available")
        }
    }
    
    /// 拍视频
    @IBAction func Pick(_ sender: Any) {
        // 1 检查相机权限
        if UIImagePickerController.isSourceTypeAvailable(.camera) {
            let vc = UIImagePickerController.init()
            vc.sourceType = .camera
            vc.mediaTypes = [kUTTypeMovie as String]
            vc.videoQuality = .typeMedium //  设置拍摄视频质量（默认：typeMedium）
            vc.videoMaximumDuration = 10.0 // 设置最长拍摄时间为10秒（默认：600秒）
            self.navigationController?.present(vc, animated: true, completion: {
            })
            vc.delegate = self as UIImagePickerControllerDelegate & UINavigationControllerDelegate
        }
        else {
            print("Camera is not available")
        }
    }
    
    
    /// 拍视频，自定义界面
    @IBAction func IMGPicker(_ sender: UIButton) {
        // 1 检查相机权限
        if UIImagePickerController.isSourceTypeAvailable(.camera) {
            let vc = UIImagePickerController.init()
            vc.sourceType = .camera
            vc.mediaTypes = [kUTTypeMovie as String]
            vc.videoQuality = .typeMedium //  设置拍摄视频质量（默认：typeMedium）
            vc.videoMaximumDuration = 10.0 // 设置最长拍摄时间为10秒（默认：600秒）
            vc.showsCameraControls = false // false的时候隐藏默认控制界面，隐藏后自己要提供控制界面才行哦
            let fram = CGRect.init(x: 0, y: vc.view.frame.maxY - 55, width: vc.view.frame.size.width, height: 55)
            let controlView = CamerControlView.init(frame:fram)
            vc.cameraOverlayView = controlView
            self.navigationController?.present(vc, animated: true, completion: {
            })
            vc.delegate = self as UIImagePickerControllerDelegate & UINavigationControllerDelegate
        }
        else {
            print("Camera is not available")
        }
        
    }
    
    
    /// 看相册
    @IBAction func ViewLibrary(_ sender: Any) {
        // Display Photo Library
        let vc = UIImagePickerController.init()
        vc.sourceType = .photoLibrary
        vc.sourceType = UIImagePickerController.SourceType.photoLibrary
        // 想看什么就加什么，比如这里既看图片又看视频，那就加两种到数组里kUTTypeMovie、kUTTypeImage
        vc.mediaTypes = [kUTTypeMovie as String,kUTTypeImage as String]
        vc.delegate = self as UIImagePickerControllerDelegate & UINavigationControllerDelegate
        
        present(vc, animated: true, completion: nil)
        
    }
}

extension ViewController:UIImagePickerControllerDelegate,UINavigationControllerDelegate {
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        // 1 The mediatype from the info dictionary is checked if it is a movie type. If this is the case the URL of the video is extracted.
        print("代理方法调用了")
        if let selectedVideo:URL = (info[UIImagePickerController.InfoKey.mediaURL] as? URL) {
            // Save video to the main photo album
            let selectorToCall = #selector(ViewController.videoSaved(_:didFinishSavingWithError:context:))

            // 2 保存视频到系统相册
            UISaveVideoAtPathToSavedPhotosAlbum(selectedVideo.relativePath, self, selectorToCall, nil)
            // 保存视频到沙盒Documents文件
            let videoData = try? Data(contentsOf: selectedVideo)
            let paths = NSSearchPathForDirectoriesInDomains(
                FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)
            let documentsDirectory: URL = URL(fileURLWithPath: paths[0])
            let dataPath = documentsDirectory.appendingPathComponent(videoFileName)
            try! videoData?.write(to: dataPath, options: [])
        }
        
        if let img:UIImage = (info[UIImagePickerController.InfoKey.originalImage] as? UIImage) {
            print("图片？")
            self.IMGPreview.image = img
            UIImageWriteToSavedPhotosAlbum(img, nil, nil, nil);
        }
        
        
        picker.dismiss(animated: true)

    }
    
    @objc func videoSaved(_ video: String, didFinishSavingWithError error: NSError!, context: UnsafeMutableRawPointer){
        if let theError = error {
            print("error saving the video = \(theError)")
        } else {
            DispatchQueue.main.async(execute: { () -> Void in
            })
        }
    }
}

